/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.seckill.multishop.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.dto.OrderRefundDto;
import com.yami.shop.bean.event.OrderRefundSuccessEvent;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.seckill.common.model.SeckillOrder;
import com.yami.shop.seckill.common.service.SeckillOrderService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 退款订单监听
 * @author lhd
 */
@Component("seckillOrderRefundListener")
@AllArgsConstructor
public class OrderRefundListener {

    private final SeckillOrderService seckillOrderService;


    /**
     * 退还用户此笔退款订单使用的优惠券
     */
    @EventListener(OrderRefundSuccessEvent.class)
    public void seckillOrderRefundSuccessEvent(OrderRefundSuccessEvent event) {
        OrderRefundDto orderRefundDto = event.getOrderRefundDto();
        //获取退款的所有订单项
        if (CollectionUtils.isEmpty(orderRefundDto.getOrderItems())) {
            return;
        }
        SeckillOrder seckillOrder = seckillOrderService.getOne(new LambdaQueryWrapper<SeckillOrder>().eq(SeckillOrder::getOrderNumber, orderRefundDto.getOrderNumber()));
        // 没有获取到对应的秒杀订单记录
        if (Objects.isNull(seckillOrder)) {
            return;
        }
        // 清除库存的缓存
        RedisUtil.del(Constant.SECKILL_SKU_STOCKS_PREFIX + seckillOrder.getSeckillSkuId());

    }
}
